package com.fishery.processing.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.processing.entity.Product;
import com.fishery.processing.mapper.CraftMapper;
import com.fishery.processing.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author run
 * @since 2021/1/14 16:42
 */
@Component
public class ProductDao {

    @Autowired
    private ProductMapper productMapper;


    public int addProduct(Product product){
        return productMapper.insert(product);
    }

    public int removeProduct(String productId){
        return productMapper.deleteById(productId);
    }

    public int updateProduct(Product product){
        return productMapper.updateById(product);
    }

    public Product findProductById(String productId){
        return productMapper.selectById(productId);
    }

    //分页查找加工厂的产品
    public IPage<Product> findProductOfFactory(String factoryId,Integer page,Integer size){
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("processing_factory_id",factoryId);
        Page<Product> productPage = new Page<>(page,size);
        return productMapper.selectPage(productPage, wrapper);
    }

    public List<Product> findProductOfFactory(String factoryId){
        Map<String,Object> map = new HashMap<>(1,1);
        map.put("processing_factory_id",factoryId);
        return productMapper.selectByMap(map);
    }

    //删除加工厂的所有产品
    public int removeProductOfFactory(String factoryId){

        //删除加工厂所有产品的连接表信息
        productMapper.removeProductOfFactory(factoryId);

        Map<String,Object> map = new HashMap<>(1,1);
        map.put("processing_factory_id",factoryId);
        return productMapper.deleteByMap(map);
    }

    public List<Product> findProductOfFactoryAndName(Product product){
        Map<String,Object> map = new HashMap<>(2,1);
        map.put("processing_factory_id",product.getProcessingFactoryId());
        map.put("product_name",product.getProductName());
        return productMapper.selectByMap(map);
    }

    public int setProductCount(String productId,Integer count){
        UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",productId).setSql("inventory = inventory + " + count);
        return productMapper.update(new Product(), wrapper);
    }



}
